package com.falm.picturebackend.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.falm.picturebackend.common.BaseResponse;
import com.falm.picturebackend.common.ResultUtils;

/**
 * 全局异常处理器
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        logger.error("RuntimeException: {} - {}", e.getMessage(), e.getClass().getName());
        logger.error("Exception stack trace: ", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ExceptionHandler(value = BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        logger.warn("BusinessException: {} - code: {}", e.getMessage(), e.getCode());
        logger.warn("Exception stack trace: ", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public BaseResponse<?> nullPointerExceptionHandler(NullPointerException e) {
        logger.error("NullPointerException: {} - {}", e.getMessage(), e.getClass().getName());
        logger.error("Exception occurred in: ", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统内部错误，请稍后重试");
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse<?> handleAllExceptions(Exception e) {
        logger.error("Unhandled exception: {} - {}", e.getMessage(), e.getClass().getName());
        logger.error("Full stack trace: ", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统内部错误，请稍后重试");
    }
}